/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ivanbiz.impl;

import com.ivanbiz.dao.PembelianDAO;
import com.ivanbiz.model.Barang;
import com.ivanbiz.model.HibernateUtil;
import com.ivanbiz.model.ItemPembelian;
import com.ivanbiz.model.Pembelian;
import com.ivanbiz.model.Piutang;
import java.util.Date;
import org.hibernate.Session;

/**
 *
 * @author User
 */
public class PembelianDAOImpl extends GenericDAOImpl implements PembelianDAO {

    public void saveTransaksiPembelian(Pembelian pembelian, double totalHarga, long tempo) throws Exception {
        try {
            HibernateUtil.beginTransaction();
            Session session = HibernateUtil.getSession();
            session.save(pembelian);
            for (int x = 0; x < pembelian.getItemPembelian().size(); x++) {
                ItemPembelian n = (ItemPembelian) pembelian.getItemPembelian().get(x);
                Barang barang = (Barang) session.load(Barang.class, n.getBarang().getId());
                barang.setStock(barang.getStock() + n.getJumlah());
                session.update(barang);
            }
            if (pembelian.getStatusPembayaran().equals("Kredit")) {
                Piutang piutang = new Piutang();
                Date date = new Date();
                date.setDate((int) (date.getDate() + tempo));
                piutang.setJatuhTempo(date);
                piutang.setPembelian(pembelian);
                piutang.setSisaPiutang(totalHarga);
                session.save(piutang);
            }
            HibernateUtil.commitTransaction();
        } catch (Exception e) {
            HibernateUtil.rollbackTransaction();
            throw e;
        } finally {
            HibernateUtil.closeSession();
        }
    }
}
